package edu.software.PBL_Management_System.util;

import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.security.MessageDigest;

@Component
public class IdEncryptionUtil {
    // 使用16字节的密钥
    private static final String SECRET_KEY = "PBLSystem1234567";  // 确保正好16个字符
    private static final String ALGORITHM = "AES";

    private final SecretKeySpec secretKey;

    public IdEncryptionUtil() {
        try {
            byte[] key = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
            // 确保密钥长度正确
            if (key.length != 16) {
                MessageDigest sha = MessageDigest.getInstance("SHA-1");
                key = sha.digest(key);
                key = java.util.Arrays.copyOf(key, 16); // 使用SHA-1后截取16字节
            }
            this.secretKey = new SecretKeySpec(key, ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException("初始化加密工具失败", e);
        }
    }

    /**
     * 加密用户ID
     * @param userId 用户ID
     * @return 加密后的字符串
     */
    public String encryptId(Long userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            // 将userId转换为字符串并加密
            byte[] encryptedBytes = cipher.doFinal(userId.toString().getBytes(StandardCharsets.UTF_8));

            // Base64编码使其URL安全，并移除可能导致URL问题的字符
            String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(encryptedBytes);
            return encoded.replaceAll("[+/=]", ""); // 移除可能在URL中有问题的字符
        } catch (Exception e) {
            throw new RuntimeException("加密用户ID失败: " + e.getMessage(), e);
        }
    }

    /**
     * 解密用户ID
     * @param encryptedId 加密后的ID字符串
     * @return 原始用户ID
     */
    public Long decryptId(String encryptedId) {
        try {
            // 添加回可能被移除的padding
            String paddedId = encryptedId;
            while (paddedId.length() % 4 != 0) {
                paddedId += "=";
            }

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // Base64解码
            byte[] decryptedBytes = cipher.doFinal(Base64.getUrlDecoder().decode(paddedId));

            // 转换回Long类型
            return Long.parseLong(new String(decryptedBytes, StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException("解密用户ID失败: " + e.getMessage(), e);
        }
    }
}
